﻿using QD.LopPlat.UI.Code;
using QD.LopPlat.UI.Code.DbContent;
using QD.LopPlat.UI.Model.Sys;
using QD.SQLHelper;
using QD.Tools;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Validation;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace QD.LopPlat.UI
{
    public partial class DataBaseMag : BaseForm
    {
        OpenWindowSimpleFrm frm;
        private PageState PageState = PageState.Browse;
        Control[] ignoreControls;
        public DataBaseMag()
        {
            InitializeComponent();

            #region 注册菜单
            base.ToolsBtnAdd = this.toolStripButton4;
            base.ToolsBtnModify = this.toolStripButton7;
            base.ToolsBtnUpdate = this.toolStripButton5;
            base.ToolsBtnDelete = this.toolStripButton11;
            base.ToolsBtnDetail = this.toolStripButton8;
            base.ToolsBtnClose = this.toolStripButton10;
            #endregion

            DataGridViewHelper.InitGrid(this.grid);
            this.grid.RowTemplate.ContextMenuStrip = this.contextMenuStrip1;

            ignoreControls = new Control[] { };
        }

        public DataBaseMag(string qfCode) : this()
        {
            InitDbBase(qfCode);
        }

        private void DataBaseManager_Load(object sender, EventArgs e)
        {
            ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, ignoreControls);
           
        }

        private void BindDb()
        {
            DbQfDevPlat dbPlat = new DbQfDevPlat();
            string key = this.txtKey.Text.Trim();
            IList<QDDataBase> dbList;
            if (!string.IsNullOrEmpty(key))
            {
                dbList = dbPlat.QDDataBase.Where(p => p.QfCode.Contains(key) || p.QfName.Contains(key)).OrderBy(p => p.QfName).ToList();
            }
            else
            {
                dbList = dbPlat.QDDataBase.OrderBy(p => p.QfName).ToList();
            }

            this.grid.DataSource = dbList;
            this.tabControl1.SelectedIndex = 1;
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            BindDb();
        }

        private void txtKey_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                toolStripButton6_Click(sender, e);
            }
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.grid.CopyFirstSelectedCellValue();
        }

        public void InitDbBase(string qfCode)
        {
            bool isInit = true;

            if (PageState != PageState.Browse && PromptHelper.PromptOkCancel("当前数据未保存，是否放弃保存？") == DialogResult.Cancel)
            {
                isInit = false;
            }
            if (isInit)
            {
                DbQfDevPlat db = new DbQfDevPlat();
                QDDataBase dbBase = db.QDDataBase.First(p => p.QfCode == qfCode);
                InitDbase(dbBase);
                this.tabControl1.SelectedIndex = 0;
                ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, ignoreControls);
                PageState = PageState.Browse;
            }
        }

        /// <summary>
        /// 显示应用信息
        /// </summary>
        /// <param name="dbBase"></param>
        private void InitDbase(QDDataBase dbBase)
        {
            this.txtQfCode.Text = dbBase.QfCode;
            this.txtQfName.Text = dbBase.QfName;
            this.txtConfigDataBase.Text = dbBase.ConfigDataBase;
            this.txtMasterDataBase.Text = dbBase.MasterDataBase;
            this.chValiImptData.Checked = dbBase.ValiImptData;
            this.chUserEnableEdit.Checked = dbBase.UserEnableEdit;
            this.chEnableSysJurnManr.Checked = dbBase.EnableSysJurnManr;
            this.txtSystemName.Text = dbBase.SystemName;
            this.txtSystemShortName.Text = dbBase.SystemShortName;
            this.txtGlobalFilterCondition.Text = dbBase.GlobalFilterCondition;
            this.txtSystemLog.Text = dbBase.Logo;
            this.txtPortNum.Text = dbBase.PortNum.ToString();
            this.chEnableStrongPwd.Checked = dbBase.EnableStrongPwd;
            this.txtSerialNumber.Text = dbBase.SerialNumber;
        }

        public override void ToolsBtnAdd_Click(object sender, EventArgs e)
        {
            ControlHelper.ClearChildValue(this.tabControl1.TabPages[0]);
            ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], false, ignoreControls);
            this.tabControl1.SelectedIndex = 0;
            this.txtPortNum.Text = "80";
            PageState = PageState.Append;
        }

        protected override void ToolsBtnDetail_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedCellCollection cells = this.grid.SelectedCells;
            if (cells.Count == 0)
            {
                PromptHelper.Prompt("请选择要查看的应用！");
            }
            else
            {
                string qfCode = this.grid.Rows[cells[0].RowIndex].Cells["QfCode"].Value.ToString();
                InitDbBase(qfCode);
            }
        }

        protected override void ToolsBtnModify_Click(object sender, EventArgs e)
        {
            ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], false, ignoreControls);
            PageState = PageState.Modify;
            this.txtQfCode.ReadOnly = true;
        }

        protected override void ToolsBtnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                if (PageState == PageState.Append || PageState == PageState.Modify)
                {
                    string qfCode = this.txtQfCode.Text.Trim();
                    string qfName = this.txtQfName.Text.Trim();

                    using (DbQfDevPlat db = new DbQfDevPlat())
                    {
                        #region 保存主表
                        QDDataBase dbMst = null;
                        if (PageState == PageState.Append)
                        {
                            dbMst = new QDDataBase();
                            dbMst.QfCode = qfCode;
                            if (db.QDDataBase.Any(p => p.QfCode == dbMst.QfCode || p.QfName == dbMst.QfName))
                            {
                                throw new Exception("应用已经存在！");
                            }
                            else
                            {
                                db.QDDataBase.Add(dbMst);
                            }
                            dbMst.CreateDate = DateTime.Now;
                        }
                        else
                        {
                            if (!db.QDDataBase.Any(p => p.QfCode == qfCode))
                            {
                                throw new Exception("应用" + qfCode + "不存在或已经被删除，操作失败！");
                            }
                            else
                            {
                                dbMst = db.QDDataBase.Single(p => p.QfCode == qfCode);
                            }
                        }
                        dbMst.QfName = qfName;
                        dbMst.ConfigDataBase = this.txtConfigDataBase.Text.Trim();
                        dbMst.MasterDataBase = this.txtMasterDataBase.Text.Trim();
                        dbMst.ValiImptData = this.chValiImptData.Checked;
                        dbMst.UserEnableEdit = this.chUserEnableEdit.Checked;
                        dbMst.EnableSysJurnManr = this.chEnableSysJurnManr.Checked;
                        dbMst.SystemName = this.txtSystemName.Text.Trim();
                        dbMst.SystemShortName = this.txtSystemShortName.Text.Trim();
                        dbMst.GlobalFilterCondition = this.txtGlobalFilterCondition.Text.Trim();
                        dbMst.Logo = this.txtSystemLog.Text.Trim();
                        dbMst.SmtpHost = this.txtSmtpHost.Text.Trim();
                        dbMst.EnableStrongPwd = this.chEnableStrongPwd.Checked;
                        dbMst.SerialNumber = this.txtSerialNumber.Text.Trim();

                        if (!string.IsNullOrEmpty(this.txtSmtpPort.Text.Trim()))
                        {
                            int _smtpPort = 0;
                            if (int.TryParse(this.txtSmtpPort.Text.Trim(), out _smtpPort))
                            {
                                dbMst.SmtpPort = _smtpPort;
                            }
                            else
                            {
                                throw new Exception("请输入正确的SMTP端口号！");
                            }
                        }
                        else
                        {
                            dbMst.SmtpPort = null;
                        }

                        int _portNum = 0;
                        if (int.TryParse(this.txtPortNum.Text.Trim(), out _portNum))
                        {
                            dbMst.PortNum = _portNum;
                            if (_portNum <= 0)
                            {
                                throw new Exception("请输入正确的Web端口");
                            }
                        }
                        else
                        {
                            throw new Exception("请输入正确的Web端口");
                        }

                        if (dbMst.QfCode.Length == 0)
                        {
                            throw new Exception("编号不能为空！");
                        }
                        else if (dbMst.QfName.Length == 0)
                        {
                            throw new Exception("名称不能为空！");
                        }
                        else if (dbMst.ConfigDataBase.Length == 0)
                        {
                            throw new Exception("配置数据库不能为空！");
                        }
                        else if (dbMst.MasterDataBase.Length == 0)
                        {
                            throw new Exception("主数据库不能为空！");
                        }
                        #endregion

                        db.SaveChanges();
                    }
                    PromptHelper.Prompt("保存成功！");

                    ControlHelper.SetChildReadonly(this.tabControl1.TabPages[0], true, ignoreControls);
                    PageState = PageState.Browse;
                    InitDbBase(qfCode);
                }
            }
            catch (DbEntityValidationException ex)
            {
                GeneralTools.EFValidaPrompt(ex);
            }
            catch (Exception ex)
            {
                PromptHelper.Prompt(ex);
            }
        }

        protected override void ToolsBtnDelete_Click(object sender, EventArgs e)

        {
            string qfCode = this.txtQfCode.Text.Trim();
            string qfName = this.txtQfName.Text.Trim();
            if (!string.IsNullOrEmpty(qfCode))
            {
                if (PromptHelper.PromptOkCancel("您正在删除应用 [" + qfCode + "] [" + qfName + "]，该方法不会删除对应的数据库,确认删除？") == DialogResult.OK)
                {
                    try
                    {
                        using (DbQfDevPlat db = new DbQfDevPlat())
                        {
                            QDDataBase mod = db.QDDataBase.FirstOrDefault(p => p.QfCode == qfCode);
                            if (mod != null)
                            {
                                string sql = string.Format(@"delete from QDDataBase where QfCode='{0}'
delete from Sys_UidRefQf where QfCode='{0}'", qfCode);

                                db.Database.ExecuteSqlCommand(sql);
                                ToolsBtnAdd_Click(sender, e);
                                BindDb();
                                PromptHelper.Prompt("应用 [" + qfCode + "] 删除成功！");
                            }
                            else
                            {
                                PromptHelper.Prompt("应用 [" + qfCode + "] 未保存或已经被删除！");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        PromptHelper.Prompt(ex);
                    }
                }
            }
            else
            {
                PromptHelper.Prompt("未加载任何应用！");
            }
        }

        private void grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.ColumnIndex > -1)
            {
                string qfCode = this.grid.Rows[e.RowIndex].Cells["QfCode"].Value.ToString();
                InitDbBase(qfCode);
            }
        }

        private void DataBaseMag_Activated(object sender, EventArgs e)
        {
            this.txtKey.Focus();
        }

        private void btn_SureClear_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确定清除选中数据？", "提示", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                QDDataBase dbBase = IsCurrentExists();
                if (dbBase != null)
                {
                    using (DbConfigData db = new DbConfigData())
                    {
                        string connectionString = DbConfig.Instance.LogonConfig.GetConnectionStrings(dbBase.ConfigDataBase);
                        string sql = "truncate table {0}";

                        #region 清理数据
                        //删除用户操作日志
                        if (this.clearUserList.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_LogLogon"));
                        }

                        //删除系统操作日志
                        if (this.clearSysLogOperation.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_LogOperation"));
                        }

                        //删除系统错误日志
                        if (this.clearSysError.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_Error"));
                        }

                        //删除短信发送日志
                        if (this.clearSysSmsLog.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_SMSLog"));
                        }

                        //删除短信限制名单
                        if (this.clearSmsLimit.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_SMSLimit"));
                        }

                        //删除计划任务执行日志
                        if (this.clearSysPlanTask.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_PlanTaskDetail"));
                        }

                        //删除表单习惯
                        if (this.clearFtHabit.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "H_FormTableDetail"));
                        }

                        //删除数据源习惯
                        if (this.clearDsHabit.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "H_DataSourceField"));
                        }

                        //删除用户自定义数据
                        if (this.clearCusmData.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_SearchConfig")); //自定义查询
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_ProgramConfig")); //自定义程序配置
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_ProCustomized")); //自定义数据格式
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_PersonalMenu")); //个人快捷菜单
                        }

                        //删除所有权限点
                        if (this.clearPernData.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_Permission"));
                        }

                        //删除用户
                        if (this.clearUid.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_UidPwd"));
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_UidRoleRel"));
                        }

                        //删除角色
                        if (this.clearRole.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_Role"));
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_RolePernRel"));
                        }

                        //角色、用户权限
                        if (this.clearPernRel.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Program_FieldLimits"));
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_RolePernRel"));
                        }

                        //系统消息
                        if (this.clearSys_Message.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_Message"));
                        }

                        //平台搜索记录
                        if (this.clearSys_QDSearchHistory.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_QDSearchHistory"));
                        }

                        if (this.clearSys_Notice.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_Notice"));
                        }

                        if (this.clearSys_ProgramUidConfig.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Sys_ProgramUidConfig"));
                        }

                        //项目进度
                        if (this.clearPMProcess.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "PM_Progress"));
                        }

                        //BUG
                        if (this.clearBUG.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Test_BUG"));
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Test_BUGProcessList"));
                        }

                        //需求
                        if (this.clearReqs.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "PM_Reqs"));
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "PM_ReqsProcessList"));
                        }

                        //程序访问记录
                        if (this.clearProgram_Usage.Checked)
                        {
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Program_Usage"));
                            db.ExecuteNonQuery(connectionString, string.Format(sql, "Program_UsageDetail"));
                        }
                        #endregion
                        MessageBox.Show("清理成功！");
                    }
                }
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("初始化应用可能会造成用户数据丢失，是否继续初始化？", "提示", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                try
                {
                    QDDataBase dbBase = IsCurrentExists();
                    if (dbBase != null)
                    {
                        string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
                        string initConfigPath = Path.Combine(rootPath, "T_SQL\\QD_V4_InitConfig.sql");

                        using (DbConfigData db = new DbConfigData())
                        {
                            string connectionString = DbConfig.Instance.LogonConfig.GetConnectionStrings(dbBase.ConfigDataBase);
                            db.ExecuteCmd(connectionString, initConfigPath, Encoding.Default);
                        }

                        string initDataPath = Path.Combine(rootPath, "T_SQL\\QD_V4_InitData.sql");

                        using (DbConfigData db = new DbConfigData())
                        {
                            string connectionString = DbConfig.Instance.LogonConfig.GetConnectionStrings(dbBase.MasterDataBase);
                            db.ExecuteCmd(connectionString, initDataPath, Encoding.Default);
                        }

                        MessageBox.Show("初始化成功！");
                    }
                }
                catch (Exception ex)
                {
                    Tools.PromptHelper.Prompt(ex);
                }
            }
        }

        private QDDataBase IsCurrentExists()
        {
            QDDataBase dbBase = null;
            string qfCode = this.txtQfCode.Text.Trim();
            if (!string.IsNullOrEmpty(qfCode))
            {
                DbQfDevPlat dbPlat = new DbQfDevPlat();
                dbBase = dbPlat.QDDataBase.FirstOrDefault(p => p.QfCode == qfCode);
                if (dbBase == null)
                {
                    MessageBox.Show("应用[" + qfCode + "]不存在或已经被删除！");
                }
            }
            else
            {
                MessageBox.Show("未选择任何应用！");
            }

            return dbBase;
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            if (PageState == PageState.Append)
            {
                frm = new OpenWindowSimpleFrm(string.Empty, null);
                frm.IsAutoClose = false;
                frm.SureEvent += frm_Copy;

                frm.ShowDialog();
            }
            else
            {
                Tools.PromptHelper.Prompt("只有在新增状态下才能使用该功能！");
            }
        }

        void frm_Copy(object sourceData, object targetData)
        {
            DbQfDevPlat db = new DbQfDevPlat();

            QDDataBase dbBase = db.QDDataBase.FirstOrDefault(p => p.QfCode == targetData.ToString());
            if (dbBase == null)
            {
                PromptHelper.Prompt("应用 [" + targetData.ToString() + "] 不存在！");
            }
            else
            {
                InitDbase(dbBase);
                this.tabControl1.SelectedIndex = 0;
                frm.Hide();
            }
        }

        private void 添加ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确认添加usp_GetPrefix？", "提示", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                try
                {
                    QDDataBase dbBase = IsCurrentExists();
                    if (dbBase != null)
                    {
                        string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
                        string initConfigPath = Path.Combine(rootPath, "T_SQL\\usp_GetPrefix.sql");

                        using (DbConfigData db = new DbConfigData())
                        {
                            string connectionString = DbConfig.Instance.LogonConfig.GetConnectionStrings(dbBase.MasterDataBase);
                            db.ExecuteCmd(connectionString, initConfigPath, Encoding.Default);
                        }

                        MessageBox.Show("添加成功！");
                    }
                }
                catch (Exception ex)
                {
                    Tools.PromptHelper.Prompt(ex);
                }
            }
        }

        private void 添加uspSysDataSyncToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("确认添加usp_Sys_DataSync？", "提示", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                try
                {
                    QDDataBase dbBase = IsCurrentExists();
                    if (dbBase != null)
                    {
                        string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
                        string initConfigPath = Path.Combine(rootPath, "T_SQL\\usp_Sys_DataSync.sql");

                        using (DbConfigData db = new DbConfigData())
                        {
                            string connectionString = DbConfig.Instance.LogonConfig.GetConnectionStrings(dbBase.MasterDataBase);
                            db.ExecuteCmd(connectionString, initConfigPath, Encoding.Default);
                        }

                        MessageBox.Show("添加成功！");
                    }
                }
                catch (Exception ex)
                {
                    Tools.PromptHelper.Prompt(ex);
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.txtGlobalFilterCondition.Text = "[!TAlias].XXX=XXX";
        }
    }
}
